/*
 * version date author 
 * �?���?���?���?���?���?���?���?���?���?���?���?���?���?���?���?���?�� 
 * 1.0 2010-9-27 Neal Miao 
 * 
 * Copyright(c) 2010, by Theotino Inc. All Rights Reserved. 
 */
package com.gmail.nealnb.sf.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;

/**
 * HTTP的工具类
 * 
 * @author Neal Miao
 * @version
 * @since v 1.0
 * @Date 2010 2010-9-27 下午01:26:12
 * 
 * @see
 */
public class HttpUtil {
	
	/**
	 * post 发请求
	 * 
	 * @param urlString
	 * @param sendMsg
	 *            version, ...
	 * @return void
	 * @since v 1.0
	 */
	public static String sendMessage(String urlString,
			Map<String, String> sendMsg) {
		try {
			URL url = new URL(urlString);
			// 使用HttpURLConnection打开连接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(8000);
			conn.setRequestProperty("Accept", "*/*");   
			conn.setRequestProperty("Connection", "Keep-Alive");   
			conn.setRequestProperty("User-Agent",   
                    "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");   
			conn.setRequestProperty("Accept-Charset", "UTF-8");  
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");  
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			conn.setDefaultUseCaches(false);
			OutputStream out = conn.getOutputStream();
			out.write(getParams(sendMsg).getBytes());
			Log.i("REQUEST", getParams(sendMsg));
			out.flush();
			out.close();
			InputStream is = conn.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			StringBuilder sb = new StringBuilder();
			String inputLine = "";
			while (((inputLine = br.readLine()) != null)) {
				sb.append(inputLine);
			}
			br.close();
			conn.disconnect();
			Log.i("RESPONSE", sb.toString());
			return sb.toString();
		} catch (SocketTimeoutException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 组装param
	 * 
	 * @param sendMsg
	 * @return String
	 * @since v 1.0
	 */
	public static String getParams(Map<String, String> sendMsg) {
		StringBuffer stringBuffer = new StringBuffer();
		for (String key : sendMsg.keySet()) {
			String value = sendMsg.get(key);
			if (null == value || 0 == value.length())
				continue;
			stringBuffer.append("&");
			stringBuffer.append(key);
			stringBuffer.append("=");
			stringBuffer.append(value);
		}
		return stringBuffer.substring(1);
	}

	/**
	 * 根据url地址获取response，并转成String
	 * 
	 * @param urlString
	 * @return String
	 * @since v 1.0
	 */
	public static String getResponseFromWeb(String urlString) {
		return getResponseFromWeb(urlString, null);
	}

	/**
	 * 根据url地址获取response，并转成String
	 * 
	 * @param urlString
	 * @param encode
	 * @return String
	 * @since v 1.0
	 */
	public static String getResponseFromWeb(String urlString, String encode) {
		StringBuffer stringBuffer = new StringBuffer();
		String rtString = "";
		InputStreamReader in;
		try {
			URL url = new URL(urlString);
			// 使用HttpURLConnection打开连接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(8000);
			conn.setReadTimeout(6000);
			conn.setDoInput(true);
			if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
				// 得到读取的内�?�?
				if (null == encode) {
					in = new InputStreamReader(conn.getInputStream());
				} else {
					in = new InputStreamReader(conn.getInputStream(), encode);
				}
				// 为输出创建BufferedReader
				BufferedReader buffer = new BufferedReader(in);
				String inputLine = "";
				// 使用循环来读取获得的数据
				while (((inputLine = buffer.readLine()) != null)) {
					stringBuffer.append(inputLine);
				}
				in.close();
				conn.disconnect();
				rtString = stringBuffer.toString();
			} else {
				rtString = "Connection Error. HTTP ResponseCode:"
						+ conn.getResponseCode();
			}
		} catch (SocketTimeoutException e) {
			return "";
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
		return rtString;
	}

	/**
	 * 根据url地址获取xml document
	 * 
	 * @param urlString
	 * @return String
	 * @since v 1.0
	 */
	public static Document getXmlFromWeb(String urlString) {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder documentBuilder;
		Document document = null;
		try {
			URL url = new URL(urlString);
			// 使用HttpURLConnection打开连接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(8000);
			conn.setReadTimeout(10000);
			conn.setDoInput(true);
			documentBuilder = factory.newDocumentBuilder();
			document = documentBuilder.parse(conn.getInputStream());
			conn.disconnect();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
			return null;
		} catch (SAXException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return document;
	}

	/**
	 * 获取bitmap
	 * 
	 * @param urlString
	 * @param scale
	 *            2==1/2
	 * @return Bitmap
	 * @since v 1.0
	 */
	public static Bitmap getImageFromWeb(String urlString, int scale) {
		Bitmap bitmap = null;
		try {
			URL url = new URL(urlString);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(8000);
			conn.setReadTimeout(6000);
			conn.setDoInput(true);
			if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
				InputStream is = conn.getInputStream();
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inJustDecodeBounds = false;
				options.inSampleSize = scale;
				bitmap = BitmapFactory.decodeStream(is, null, options);
				// int orgWidth = bitmap.getWidth();
				// int orgHeight = bitmap.getHeight();
				// // 缩放图片的尺寸
				// float scale = (float) orgWidth
				// / AppCache.deviceInfo.getScreenWidth();
				// Matrix matrix = new Matrix();
				// matrix.postScale(scale, scale);
				// // 产生缩放后的Bitmap对象
				// Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0,
				// orgWidth, orgHeight, matrix, false);
				// bitmap = resizeBitmap;
			}
			conn.disconnect();
		} catch (SocketTimeoutException e) {
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return bitmap;
	}

	/**
	 * 获取Drawable
	 * 
	 * @param url
	 * @return Drawable
	 * @since v 1.0
	 */
	public static Drawable getDrawableFromWeb(String urlString, int scale) {
		/*
		 * InputStream inputStream = null; try { inputStream = (InputStream) new
		 * URL(url).getContent(); } catch (MalformedURLException e1) {
		 * e1.printStackTrace(); } catch (IOException e) { e.printStackTrace();
		 * }
		 */
		BitmapDrawable bitmapDrawable = new BitmapDrawable(getImageFromWeb(
				urlString, scale));
		return bitmapDrawable;
	}

	/**
	 * 从网络上直接保存图片到sdcard
	 * 
	 * @param urlString
	 * @param toPath
	 *            end with '/'
	 * @param newName
	 * @return void
	 * @since v 1.0
	 */
	public static void saveImageFromWeb(String urlString, String toPath,
			String newName) {
		try {
			File tmp = new File("/sdcard/" + toPath);
			if (!tmp.exists()) {
				tmp.mkdir();
			}
			URL url = new URL(urlString);
			FileOutputStream fOut = new FileOutputStream("/sdcard/" + toPath
					+ newName);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(8000);
			conn.setDoInput(true);
			if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
				InputStream is = conn.getInputStream();
				byte buffer[] = new byte[1024];
				int count = 0;
				while ((count = is.read(buffer)) > 0) {
					fOut.write(buffer, 0, count);
				}
			}
			fOut.flush();
			fOut.close();
			conn.disconnect();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 测试图片是否存在
	 * 
	 * @param path
	 * @return boolean
	 * @since v 1.0
	 */
	public static boolean tryConnection(String path) {
		URL url;
		HttpURLConnection conn = null;
		try {
			url = new URL(path);
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			conn.getInputStream();
			return true;
		} catch (Exception e) {
			return false;
		} finally {
			conn.disconnect();
		}
	}

	/**
	 * 检测网络情况
	 * 
	 * @return boolean true 可用 false 不可用
	 * @since v 1.0
	 */
	public static boolean serverPDAIsAvailable(String ip) {
		return serverIsAvailable("http://" + ip + "/pda/getdata.aspx?");
	}

	/**
	 * 检测网络情况
	 * 
	 * @return boolean true 可用 false 不可用
	 * @since v 1.0
	 */
	public static boolean serverIsAvailable(String urlStr) {
		HttpURLConnection conn = null;
		try {
			URL url = new URL(urlStr);
			// 使用HttpURLConnection打开连接
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(3000);
			conn.setDoInput(true);
			if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
				return true;
			}
		} catch (SocketTimeoutException e2) {
			e2.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			if (null != conn) {
				conn.disconnect();
			}
		}
		return false;
	}

	/**
	 * 
	 * @param urlStr
	 * @param path
	 * @param fileName
	 * @return -1:文件下载出错 0:文件下载成功 1:文件已经存在
	 */
	public static int downFile(String urlStr, String path, String fileName) {
		InputStream inputStream = null;
		try {
			FileUtils fileUtils = new FileUtils();
			if (fileUtils.isFileExist(path + fileName)) {
				return 1;
			} else {
				inputStream = getInputStreamFromURL(urlStr);
				File resultFile = fileUtils.write2SDFromInput(path, fileName,
						inputStream);
				if (resultFile == null) {
					return -1;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		} finally {
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return 0;
	}

	/**
	 * 根据URL得到输入流
	 * 
	 * @param urlStr
	 * @return
	 */
	public static InputStream getInputStreamFromURL(String urlStr) {
		HttpURLConnection urlConn = null;
		InputStream inputStream = null;
		try {
			URL url = new URL(urlStr);
			urlConn = (HttpURLConnection) url.openConnection();
			inputStream = urlConn.getInputStream();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return inputStream;
	}

	public static boolean download(String urlString, String path,
			String fileName) {

		// set the download URL, a url that points to a file on the internet
		// this is the file to be downloaded
		URL url;
		try {
			url = new URL(urlString);
			// create the new connection
			HttpURLConnection urlConnection = (HttpURLConnection) url
					.openConnection();

			// set up some things on the connection
			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);

			// and connect!
			urlConnection.connect();
			// set the path where we want to save the file
			// in this case, going to save it on the root directory of the
			// sd card.
			// File SDCardRoot = Environment.getExternalStorageDirectory();
			// create a new file, specifying the path, and the filename
			// which we want to save the file as.
			File file = new File(path + fileName);
			if (!file.exists()) {
				file.createNewFile();
			}
			// this will be used to write the downloaded data into the file we
			// created
			FileOutputStream fileOutput = new FileOutputStream(file);

			// this will be used in reading the data from the internet
			InputStream inputStream = urlConnection.getInputStream();

			urlConnection.getContentLength();
			// variable to store total downloaded bytes
			int downloadedSize = 0;

			// create a buffer...
			byte[] buffer = new byte[1024];
			int bufferLength = 0; // used to store a temporary size of the
			// buffer

			// now, read through the input buffer and write the contents to the
			// file
			while ((bufferLength = inputStream.read(buffer)) > 0) {
				// add the data in the buffer to the file in the file output
				// stream (the file on the sd card
				fileOutput.write(buffer, 0, bufferLength);
				// add up the size so we know how much is downloaded
				downloadedSize += bufferLength;
				// this is where you would do something to report the prgress,
				// like this maybe
				// updateProgress(downloadedSize, totalSize);

			}
			// close the output stream when done
			fileOutput.close();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// install();
		return true;
	}
}
